package com.heima.comment.service.impl;

import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.vos.ApCommentRepayVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;


    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1 参数检查
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }

        // size=10
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            dto.setSize(10);
        }

        //2 查询评论列表
        List<ApCommentRepay>  apCommentRepayList =mongoTemplate.find(Query.query(Criteria
                        .where("commentId").is(dto.getCommentId())
                        .and("createdTime").lt(dto.getMinDate()))
                        .limit(dto.getSize())
                        .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                , ApCommentRepay.class);
        //3 处理 评论点赞回显
        // 如果当前用户未登录，直接返回
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentRepayList);
        }

        // 如果用户登录，处理回显
        // 获取当前文章的所有的评论id
        List<String> idList = apCommentRepayList.stream().map(comment -> comment.getId())
                .collect(Collectors.toList());
        // 返回回显的评论带点赞
        List<ApCommentRepayVo> apCommentRepayVos = new ArrayList<>();
        if (idList != null && idList.size() > 0) {  // 评论列表 select * from ta where commentId in()

            Query query = Query.query(Criteria.where("commentRepayId").in(idList)
                    .and("authorId").is(user.getId()).and("operation").is(0));

            List<ApCommentRepayLike> commentRepayLikeList = mongoTemplate.find(query, ApCommentRepayLike.class);

            if (commentRepayLikeList != null && commentRepayLikeList.size() > 0) {  // 有点赞
                // 评论列表
                apCommentRepayList.forEach( apCommentRepay -> {

                    ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                    BeanUtils.copyProperties(apCommentRepay, apCommentRepayVo);

                    // 评论点赞列表
                    commentRepayLikeList.forEach(commentRepayLike->{
                        // 判断点赞
                        if (apCommentRepay.getId().equals(commentRepayLike.getCommentRepayId()) && commentRepayLike.getOperation() == 0) {
                            apCommentRepayVo.setOperation((short) 0);
                        }
                    });
                    apCommentRepayVos.add(apCommentRepayVo);
                } );

                return ResponseResult.okResult(apCommentRepayVos);
            }else {
                return ResponseResult.okResult(apCommentRepayList);
            }
        }

        //4 返回数据
        return ResponseResult.okResult(apCommentRepayList);
    }

    /**
     * 保存回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1 参数检查
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 文章评论内容
        if (StringUtils.isBlank(dto.getContent()) || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取当前登录人
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 查询APUser用户信息
        Integer loginUserId = user.getId();
        user = userFeign.findUserById(loginUserId.longValue());
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "非法账号");
        }

        // 内容安全检查 （自行实现）


        //2 保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setAuthorId(loginUserId);
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.save(apCommentRepay);


        // ***** 更新回复数
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);


        //3 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //1 参数检查
        if (dto == null || dto.getCommentRepayId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取当前登录人
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 查询APUser用户信息
        Integer loginUserId = user.getId();
        user = userFeign.findUserById(loginUserId.longValue());
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "非法账号");
        }

        // 查询评论
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "暂无评论");
        }

        // 用户是否重重复点赞
        Query query = Query.query(Criteria
                .where("commentRepayId").is(dto.getCommentRepayId())
                .and("authorId").is(user.getId())
        );
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (commentRepayLike != null && dto.getOperation()==0  && commentRepayLike.getOperation()==0 ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已点赞");
        }

        //3 保存点赞
        if (commentRepayLike == null && dto.getOperation().intValue() == 0) { // 第一次点赞

            // 保存点赞评论信息
            commentRepayLike = new ApCommentRepayLike();
            commentRepayLike.setAuthorId(user.getId());
            commentRepayLike.setCommentRepayId(commentRepay.getId());
            commentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(commentRepayLike);

            // 更新点赞数
            commentRepay.setLikes(commentRepay.getLikes() + 1);
            mongoTemplate.save(commentRepay);

        } else { // 取消点赞

            commentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(commentRepayLike);


            commentRepay.setLikes(commentRepay.getLikes() <= 1 ? 0 : commentRepay.getLikes() - 1);
            mongoTemplate.save(commentRepay);
        }

        //4 返回结果
        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes", commentRepay.getLikes());

        return ResponseResult.okResult(resultMap);
    }
}

